﻿using System.IO;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Collections.Generic;
using System;
using System.Drawing;
using System.Linq;

namespace chemmind
{
    public partial class Form1 : Form
    {
        
        // 缓存图表数据
        private readonly Dictionary<string, ChartData> _chartDataCache = new Dictionary<string, ChartData>();
        
        public Form1()
        {
            InitializeComponent();
            InitializeCharts();
        }
        
        // 初始化图谱
        private void InitializeCharts()
        {
            List<ChartData> charts = LoadChartData();
            foreach (ChartData chartData in charts)
            {
                // 更新缓存
                if (!_chartDataCache.ContainsKey(chartData.Title))
                {
                    _chartDataCache[chartData.Title] = chartData;
                }
                Chart chart = new Chart();
                ((System.ComponentModel.ISupportInitialize)(chart)).BeginInit();
                ChartArea chartArea = new ChartArea();
                Legend legend = new Legend();
                Series series = new Series();
                chart.ChartAreas.Add(chartArea);
                chart.Legends.Add(legend);
                chart.Location = new System.Drawing.Point(3, 3);

                for (var i = 0; i < chartData.Points.Count; i++)
                {
                    var point = chartData.Points[i];
                    series.Points.AddY(point.Y);
                    // 如果数据是修改后的，那么就改为红色
                    if (point.Changed)
                    {
                        series.Points[i].Color = Color.Red;
                    }
                }

                series.Name = chartData.Title;
                Title title = new Title();
                title.Name = "name";
                title.Text = chartData.Title;
                chart.Titles.Add(title);
                chart.Series.Add(series);
                chart.Name = chartData.Title;
                chart.Size = new Size(150, 150);
                chart.Click += chart_Click;
                layoutPanel.Controls.Add(chart);
            }
        }

        private void chart_Click(object sender, EventArgs e)
        {
            var clickedChart = sender as Chart;
            if (clickedChart == null) return;
            var chartInfo = new ChartInfo(clickedChart);
            chartInfo.DataChanged += ChartInfo_DataChanged;
            chartInfo.Show();
        }

        private void ChartInfo_DataChanged(object sender, DataChangedEventArgs e)
        {
            if (!(sender is ChartInfo chartInfo) || chartInfo.Chart == null) return;
            // 找到对应的主窗体图表
            var mainChart = FindMainChart(chartInfo.Chart);

            if (mainChart != null && _chartDataCache.TryGetValue(mainChart.Name, out var chartData))
            {
                // 更新主窗体图表中的数据点
                foreach (var series in mainChart.Series)
                {
                    // 更新拖动的数据点
                    if (e.DraggedPoint.Index < series.Points.Count)
                    {
                        var draggedPoint = series.Points[e.DraggedPoint.Index];
                        draggedPoint.YValues[0] = e.DraggedPoint.YValue;
                        draggedPoint.XValue = e.DraggedPoint.XValue;
                        draggedPoint.Color = e.DraggedPoint.Color;
                    }

                    // 更新目标的数据点
                    if (e.TargetPoint.Index < series.Points.Count)
                    {
                        var targetPoint = series.Points[e.TargetPoint.Index];
                        targetPoint.YValues[0] = e.TargetPoint.YValue;
                        targetPoint.XValue = e.TargetPoint.XValue;
                        targetPoint.Color = e.TargetPoint.Color;
                    }
                }

                // 刷新主窗体图表
                mainChart.Invalidate();
                
                // 获取所有图表的最新数据
                UpdateChartCache(mainChart, chartData);

                // 保存更新后的图表数据到 JSON 文件
                SaveChartData(new List<ChartData>(_chartDataCache.Values));
            }
        }

        // 更新缓存数据
        private void UpdateChartCache(Chart chartToUpdate, ChartData chartData)
        {
            foreach (var series in chartToUpdate.Series)
            {
                var points = series.Points;
                for (var i = 0; i < points.Count; i++)
                {
                    var chartDataPoint = chartData.Points[i];
                    chartDataPoint.X = points[i].XValue;
                    chartDataPoint.Y = points[i].YValues.First();
                    chartDataPoint.Changed = points[i].Color == Color.Red;
                }
                _chartDataCache[chartData.Title] = chartData;
            }
        }

        
        // 在主窗体中找到 chart
        private Chart FindMainChart(Chart childChart)
        {
            foreach (Control control in layoutPanel.Controls)
            {
                if (!(control is Chart chart)) continue;
                // 根据 title 查询主窗体的具体 chart
                if (chart.Name == childChart.Name)
                {
                    return chart;
                }
            }

            return null;
        }

        // 加载本地文件
        private static List<ChartData> LoadChartData()
        {
            var jsonData = File.ReadAllText("chart.json");
            return JsonConvert.DeserializeObject<List<ChartData>>(jsonData);
        }

        // 保存文件
        private static void SaveChartData(List<ChartData> charts)
        {
            var jsonData = JsonConvert.SerializeObject(charts, Formatting.Indented);
            File.WriteAllText("chart.json", jsonData);
        }
    }
}